
import java.awt.*;
import java.awt.event.KeyEvent;
import java.util.LinkedList;

public class Snake {
    private LinkedList<Point> body; // 蛇的身体
    private int direction; // 蛇的方向
    private int gridWidth; // 网格宽度
    private int gridHeight; // 网格高度
    private int tileSize; // 每个方块的大小

    public Snake(int gridWidth, int gridHeight, int tileSize) {
        this.gridWidth = gridWidth;
        this.gridHeight = gridHeight;
        this.tileSize = tileSize;
        body = new LinkedList<>(); // 初始化蛇的身体
        body.add(new Point(5, 5)); // 添加蛇头
        body.add(new Point(4, 5)); // 添加身体部分
        body.add(new Point(3, 5)); // 添加身体部分
        direction = KeyEvent.VK_RIGHT; // 初始方向为右
    }

    public void changeDirection(int keyCode) {
        // 改变方向，避免反向
        if ((keyCode == KeyEvent.VK_LEFT && direction != KeyEvent.VK_RIGHT) ||
                (keyCode == KeyEvent.VK_RIGHT && direction != KeyEvent.VK_LEFT) ||
                (keyCode == KeyEvent.VK_UP && direction != KeyEvent.VK_DOWN) ||
                (keyCode == KeyEvent.VK_DOWN && direction != KeyEvent.VK_UP)) {
            direction = keyCode; // 更新方向
        }
    }

    public void move() {
        Point head = body.getFirst(); // 获取蛇头
        Point newHead = new Point(head); // 创建新的蛇头

        // 根据方向移动蛇头
        switch (direction) {
            case KeyEvent.VK_UP:
                newHead.y--; // 向上移动
                break;
            case KeyEvent.VK_DOWN:
                newHead.y++; // 向下移动
                break;
            case KeyEvent.VK_LEFT:
                newHead.x--; // 向左移动
                break;
            case KeyEvent.VK_RIGHT:
                newHead.x++; // 向右移动
                break;
        }

        body.addFirst(newHead); // 将新的蛇头添加到身体前面
        body.removeLast(); // 移除蛇尾
    }

    public void grow() {
        body.addLast(new Point(body.getLast())); // 在蛇尾添加一个新的身体部分
    }

    public boolean checkCollisionWithFood(Food food) {
        return body.getFirst().equals(food.getPosition()); // 检查是否吃到食物
    }

    public boolean checkCollisionWithWall() {
        Point head = body.getFirst(); // 获取蛇头
        return head.x < 0 || head.x >= gridWidth || head.y < 0 || head.y >= gridHeight; // 检查是否碰到墙壁
    }

    public boolean checkCollisionWithSelf() {
        Point head = body.getFirst(); // 获取蛇头
        for (int i = 1; i < body.size(); i++) {
            if (head.equals(body.get(i))) { // 检查是否碰到自己
                return true;
            }
        }
        return false; // 没有碰到自己
    }

    public void draw(Graphics g) {
        boolean isHead = true; // 标记是否为蛇头
        for (Point point : body) {
            if (isHead) {
                g.setColor(Color.GREEN); // 蛇头为绿色
                isHead = false; // 之后的部分为身体
            } else {
                g.setColor(Color.YELLOW); // 蛇身为黄色
            }
            g.fillRect(point.x * tileSize, point.y * tileSize, tileSize, tileSize); // 绘制蛇的每个部分
        }
    }
}